package com.pingan.haofang.searchcloud.batch.config;

import com.pingan.haofang.searchcloud.batch.constants.RunnerNameConstants;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class ScheduleConfiguration {

    @Autowired
    private JobFactory jobFactory;

    @Autowired
    DataSource dataSource;

    @Value("${quartz.scheduler.instanceName:scheduler}")
    String instanceName;


    private Properties properties(String propertyName) throws IOException {
        Properties prop = new Properties();
        prop.load(new ClassPathResource(propertyName).getInputStream());
        return prop;
    }

    @Bean
    @ConditionalOnProperty(RunnerNameConstants.FULL_TASK)
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(properties("/quartz-worker-fulltask.properties"));
        factory.setSchedulerName(instanceName);
        factory.setDataSource(dataSource);
        factory.setJobFactory(jobFactory);
        factory.setOverwriteExistingJobs(true);
        return factory;
    }


    @Bean
    @ConditionalOnMissingBean(type = "org.quartz.Scheduler")
    public SchedulerFactoryBean schedulerFactory() throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setQuartzProperties(properties("/quartz-worker-inctask.properties"));
        bean.setOverwriteExistingJobs(true);
        return bean;
    }

}
